const fs = require('fs')
const path = require('path')
const nodexlsx = require('node-xlsx')//引入模块

const config = { //配置信息 在阿里云管理控制台头像
  accessKeyId: 'LTAI5t79cgigBqJxf6Dgx7Zp',
  accessKeySecret: 'nnah5hvN28R0gpotvrRUbfhCULDtMC',
  endpoint: 'https://codeup.cn-hangzhou.aliyuncs.com',
  apiVersion: '2020-04-14'
}
//Api 示例
var ROAClient = require('@alicloud/pop-core').ROAClient;
var client = new ROAClient(config);

var uriPath = '/api/v3/projects/all'; //获取仓库地址
var queries = {
  "AccessToken": "agp_fc6f467a415982b0af2448a18cb3558b",
  "OrganizationId": "5f02ba8062b03dd98afb1b75",//项目路径中间的一段
};

//获取仓库信息
async function getProjectsAll(httpMethod, uriPath, queries) {
  return client.request(httpMethod, uriPath, queries)
}

var datas = [];//xlsx
var title = [];//xlsx
//获取各个项目分支信息
async function getBranches() {
  const res = await getProjectsAll('GET', uriPath, queries);
  //xlsx表头
  res.Result.forEach(t => {
    if (t.Description != '' && t.Description != null) {
      title.push(t.Description)
    } else if (t.Name != '' && t.Name != null) {
      title.push(t.Name)
    }
  })
  datas.push(title)

  //client.request 返回的就是promise 
  var proArr = res.Result.map(item => {
    return client.request('GET', `/api/v3/projects/${item.Id}/repository/branches`, queries)
  });
  return proArr;
}


module.exports = async (log) => {
  //client.request 返回的就是promise 
  Promise.all(await getBranches()).then(res => {
    var arr;
    res.forEach(d => {
      arr = [];
      d.Result.forEach(data => {
        arr.push(data.BranchName)
      })
      datas.push(arr)
    })

    //生成表格
    var buffer = nodexlsx.build([{ name: 'sheet1', data: datas }]);
    // var filePath = path.join(__dirname, '../text2.xlsx');
    var filePath = path.resolve('./exct/text.xlsx');
    if (!fs.existsSync('exct')) {
      fs.mkdirSync('exct')
    }
    console.log(filePath);
    fs.writeFileSync(filePath, buffer, { 'flag': 'w' });
  })
}